package com.itheima.filter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

// 1. 使用Order注解，设置执行顺序
@Order(-1)
@Component
// 2. 要实现GlobalFilter声明全局过滤器
public class AuthorizeFilter implements GlobalFilter {

    @Autowired
    private Config config;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getHeaders();

        List<String> whitelist = config.getWhite();
        //针对个别接口放行的功能
        //1.获取当前请求的地址
        String url = exchange.getRequest().getPath().toString();
        //2.判断这个地址是不是放行
        if (whitelist.contains(url)){
            System.out.println("放行");
            return chain.filter(exchange);
        }


        // 2.获取authorization参数
        String token = params.getFirst("authorization");
        //3.解析token信息
        boolean verify = JWTUtil.verify(token, "tanhua".getBytes());
        if (!verify){
            //阻止
            return getVoidMono(exchange);
        }
        //4.获取用户信息
        JWT jwt = JWTUtil.parseToken(token);
        //获取载荷
        JWTPayload payload = jwt.getPayload();
        if (payload==null){
            //阻止
            return getVoidMono(exchange);
        }
        //获取里面的id字段
        Object id = payload.getClaim("id");
        if (id==null){
            //阻止
            return getVoidMono(exchange);
        }
        //放行
        System.out.println("放行成功");
        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange){
        //1.获取响应结构，设置状态
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        //2.把修改后的返回值结果，响应给前端
        return exchange.getResponse().setComplete();
    }
}